package com.zx.mes.hyl.controller;

import com.alibaba.fastjson.JSON;
import com.zx.mes.hyl.common.exception.BaseException;
import com.zx.mes.hyl.common.msg.ObjectRestResponse;
import com.zx.mes.hyl.common.msg.TableResultResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipInputStream;

/**
 * 部署相关的 api
 * @author hyl
 * @date 2018-5-18
 */
@Api(tags = "工作流部署")
@RestController
@RequestMapping("/deployment")
public class DeploymentController {

    private Logger logger = LoggerFactory.getLogger(DeploymentController.class);

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @ApiOperation("部署分页列表")
    @GetMapping("/page")
    public TableResultResponse<com.zx.mes.hyl.pagemodel.Deployment> deployemnts(@ApiParam("从第几页开始(下标0开始)") int firstResult,
                                                                                @ApiParam("每页多少条") int maxResults ){
        List<Deployment> deploymentList = repositoryService.createDeploymentQuery()
                .listPage(firstResult, maxResults);
        List<com.zx.mes.hyl.pagemodel.Deployment> list = new ArrayList<>();
        for (int i = 0; i < deploymentList.size(); i++) {
            com.zx.mes.hyl.pagemodel.Deployment deployment = new com.zx.mes.hyl.pagemodel.Deployment();
            BeanUtils.copyProperties(deploymentList.get(i),deployment);
            list.add(deployment);
        }
        logger.info(JSON.toJSONString(list));
        return new TableResultResponse<>(list.size(),list);
    }

    @ApiOperation("上传与部署")
    @PostMapping("/add")
    public ObjectRestResponse<String> uploadAndDeployment(@ApiParam("文件")@RequestParam("file") MultipartFile file){
        String fileName = file.getOriginalFilename();
        try {
            ZipInputStream inputStream = new ZipInputStream(file.getInputStream());
            repositoryService.createDeployment()
                    .name(fileName)
                    .addZipInputStream(inputStream)
                    .deploy();
        } catch (IOException e) {
            throw new BaseException("获取上传文件异常:"+e.getMessage());
        }
        return new ObjectRestResponse<>().rel(true).data("部署成功");
    }

    @ApiOperation("删除一个流程部署")
    @DeleteMapping("/delete/{id}")
    public ObjectRestResponse<String> delete(@ApiParam("流程部署ID") @PathVariable String id){

        repositoryService.deleteDeployment(id);
        return new ObjectRestResponse<>().rel(true).data("删除一个部署成功!");
    }


    @ApiOperation("启动一个部署实例")
    @PostMapping("/start/{id}")
    public ObjectRestResponse<String> startProcessInstanceByKey(@ApiParam("流程部署ID") @PathVariable String id){
        return null;
    }

    @ApiOperation("自定义全局异常处理测试")
    @GetMapping("/exception")
    public ObjectRestResponse<String> testException(int i){

        if (i>0){

        }else {
            throw new BaseException("捕获异常");
        }
        return new ObjectRestResponse<>().data("方法返回");
    }
}
